<script setup>
    import courseApi from "@/api/course.js";
    import {ref} from "vue";
    import {ElMessage, ElMessageBox} from "element-plus";
    import {Download, Delete, Plus, Upload} from '@element-plus/icons-vue'
    import coachApi from "@/api/coach.js";
    import reserveApi from "@/api/reserve.js";

    import {useUserInfoStore} from '@/store/userInfo.js'
    const userInfoStore = useUserInfoStore()
    const userId = userInfoStore.user.id //从userInfoStore（pinia取出用户id）

    //数据表格
    const list = ref([])//当前页数据
    const total = ref(0)//总条目数

    //分页信息和搜索条件
    const courseQuery = ref({
        name: '',
        userId: '',
        coachId: '',
        page: 1,
        limit: 10
    })

    const loadData = () => {//加载数据，分页查找
        courseApi.list(courseQuery.value).then(result => {
            if (result.code == 0) {
                list.value = result.data.records//当前页数据
                total.value = result.data.total//总条目数
            }
        })
    }

    loadData()//调用

    //条件查找，拼接条件在后端mapper已经实现
    const onSearch = () => {
        courseQuery.value.page = 1
        loadData()
    }

    //重置搜索框为空
    const reset = () => {
        courseQuery.value.name = ''
        courseQuery.value.coachId = ''
    }

    // 添加预约
    /*const showAddDialog = (courseId) => {
        // 准备预约数据（只需要 courseId 和 userId）
        const reserveData = {
            courseId: courseId,  // 当前行的课程ID
            userId: userId       // 当前登录用户的ID（从 Pinia 获取）
        };
        // 直接调用 reserveApi.add 提交预约
        reserveApi.add(reserveData)
            .then(result => {
                if (result.code === 0) {
                    ElMessage.success("预约成功！");
                    loadData(); // 刷新课程列表
                } else {
                    ElMessage.error(result.msg || "预约失败");
                }
            })
    };*/
    // 添加预约
    const reservedCourseIds = ref(new Set());
    // 初始化已预约课程
    const initReservedCourses = () => {
        reserveApi.listByUserId(userId).then(result => {
            if (result.code === 0) {
                result.data.records.forEach(item => {
                    reservedCourseIds.value.add(item.courseId);
                });
            }
        });
    };
    // 添加预约
    const showAddDialog = (courseId) => {
        if (reservedCourseIds.value.has(courseId)) {
            ElMessage.warning("您已预约该课程，不可重复预约！");
            return;
        }

        const reserveData = { courseId, userId };
        reserveApi.add(reserveData).then(result => {
            if (result.code === 0) {
                ElMessage.success("预约成功！");
                reservedCourseIds.value.add(courseId);
                loadData();
            } else {
                ElMessage.error(result.msg || "预约失败");
            }
        });
    };
    initReservedCourses(); // 初始化

    // 页面加载时初始化
    initReservedCourses();

    //图片上传
    const handleAvatarSuccess = (result) => {//result是从后端接收是阿里云返回的图片url
        course.value.image = result.data;
    }

    import {useTokenStore} from '@/store/token.js'
    const tokenStore = useTokenStore();
    const headers = ref({
        //携带token传递到后端
        Authorization: tokenStore.token
    });

    //查找所有的教练
    const coachList = ref([])
    coachApi.selectAll().then(result => {
        if (result.code == 0) {
            coachList.value = result.data
        }
    })

    //下拉事件
    const selectChange = (value) => {
        console.log(value)
    }

</script>

<template>
    <el-card class="">
        <el-form :inline="true">
            <el-form-item label="课程名">
                <el-input v-model="courseQuery.name" placeholder="请输入课程名" clearable style="width: 200px"/>
            </el-form-item>
            <el-form-item label="教练">
                <el-select @change="selectChange" v-model="courseQuery.coachId" placeholder="请选择教练" clearable
                           style="width: 240px">
                    <el-option
                        v-for="coach in coachList"
                        :key="coach.id"
                        :label="coach.name"
                        :value="coach.id"
                    />
                </el-select>
            </el-form-item>
            <!--courseQuery里没有beginUpdateTime这两个属性，后端java代码CourseQuery对象里一定要加上，但是vue很智能会自动加上，所以前端代码ref里不用写也可以-->
            <el-form-item label="更新时间" :label-width="100">
                <el-date-picker
                    v-model="courseQuery.beginUpdateTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="开始时间"
                />
                <el-date-picker
                    v-model="courseQuery.endUpdateTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="结束时间"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">搜索</el-button>
                <el-button type="warning" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column fixed prop="id" label="ID"/>
            <el-table-column prop="name" label="课程名"/>
            <el-table-column prop="coachId" label="教练ID"/>
            <el-table-column prop="coachName" label="教练"/>
            <el-table-column prop="time" label="课程时间" width="180px"/>
            <el-table-column prop="length" label="课程时长"/>
            <el-table-column prop="maxCount" label="最大人数"/>
            <el-table-column prop="room" label="教室"/>
            <el-table-column prop="image" label="封面">
                <template #default="scope">
                    <img :src="scope.row.image" style="max-height: 40px; max-width: 120px;"/>
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="180px"/>
            <el-table-column align="center" width="200px" fixed="right" label="操作">
                <template #default="{ row }"><!--解构赋值-->
                    <el-button size="small" type="primary" @click="showAddDialog(row.id)" :disabled="reservedCourseIds.has(row.id)">
                    {{ reservedCourseIds.has(row.id) ? "已预约" : "预约" }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--底部分页-->
        <el-pagination
            v-model:current-page="courseQuery.page"
            v-model:page-size="courseQuery.limit"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @change="loadData"
            style="margin-top: 20px; justify-content: flex-end"
        />
    </el-card>
</template>

<style scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>